package com.ruoyi.medication.service.impl;

import java.util.List;
import java.util.Date;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Set;
import java.util.HashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.medication.mapper.MedicationStockMapper;
import com.ruoyi.medication.domain.MedicationStock;
import com.ruoyi.medication.service.IMedicationStockService;
import com.ruoyi.medication.mapper.MedicationMapper;
import com.ruoyi.medication.domain.Medication;

/**
 * 药物库存Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-12
 */
@Service
public class MedicationStockServiceImpl implements IMedicationStockService {
  @Autowired
  private MedicationStockMapper medicationStockMapper;

  @Autowired
  private MedicationMapper medicationMapper;

  /**
   * 查询药物库存
   * 
   * @param id 药物库存主键
   * @return 药物库存
   */
  @Override
  public MedicationStock selectMedicationStockById(Long id) {
    return medicationStockMapper.selectMedicationStockById(id);
  }

  /**
   * 根据药品ID查询库存
   * 
   * @param medicationId 药品ID
   * @return 药物库存
   */
  @Override
  public List<MedicationStock> selectMedicationStockByMedicationId(Long medicationId) {
    return medicationStockMapper.selectMedicationStockByMedicationId(medicationId);
  }

  /**
   * 查询药物库存列表
   * 
   * @param medicationStock 药物库存
   * @return 药物库存
   */
  @Override
  public List<MedicationStock> selectMedicationStockList(MedicationStock medicationStock) {
    return medicationStockMapper.selectMedicationStockList(medicationStock);
  }

  /**
   * 查询有效库存列表（未过期且数量大于0）
   * 
   * @return 药物库存集合
   */
  @Override
  public List<MedicationStock> selectValidStocks() {
    return medicationStockMapper.selectValidStocks();
  }

  /**
   * 更新药品的总库存和平均单价
   * 
   * @param medicationId 药品ID
   */
  private void updateMedicationStockAndPrice(Long medicationId) {
    List<MedicationStock> stocks = medicationStockMapper.selectMedicationStockByMedicationId(medicationId);
    if (stocks != null && !stocks.isEmpty()) {
      Long totalQuantity = 0L;
      BigDecimal totalValue = BigDecimal.ZERO;

      for (MedicationStock stock : stocks) {
        totalQuantity += stock.getQuantity();
        totalValue = totalValue.add(stock.getPrice().multiply(new BigDecimal(stock.getQuantity())));
      }

      Medication medication = medicationMapper.selectMedicationById(medicationId);
      if (medication != null) {
        medication.setStock(totalQuantity);
        if (totalQuantity > 0) {
          medication.setPrice(totalValue.divide(new BigDecimal(totalQuantity), 2, RoundingMode.HALF_UP));
        }
        medicationMapper.updateMedication(medication);
      }
    }
  }

  /**
   * 新增药物库存
   * 
   * @param medicationStock 药物库存
   * @return 结果
   */
  @Override
  public int insertMedicationStock(MedicationStock medicationStock) {
    medicationStock.setCreateTime(new Date());
    int result = medicationStockMapper.insertMedicationStock(medicationStock);
    if (result > 0) {
      updateMedicationStockAndPrice(medicationStock.getMedicationId());
    }
    return result;
  }

  /**
   * 修改药物库存
   * 
   * @param medicationStock 药物库存
   * @return 结果
   */
  @Override
  public int updateMedicationStock(MedicationStock medicationStock) {
    medicationStock.setUpdateTime(new Date());
    int result = medicationStockMapper.updateMedicationStock(medicationStock);
    if (result > 0) {
      updateMedicationStockAndPrice(medicationStock.getMedicationId());
    }
    return result;
  }

  /**
   * 批量删除药物库存
   * 
   * @param ids 需要删除的药物库存主键
   * @return 结果
   */
  @Override
  public int deleteMedicationStockByIds(Long[] ids) {
    Set<Long> medicationIds = new HashSet<>();
    for (Long id : ids) {
      MedicationStock stock = medicationStockMapper.selectMedicationStockById(id);
      if (stock != null) {
        medicationIds.add(stock.getMedicationId());
      }
    }

    int result = medicationStockMapper.deleteMedicationStockByIds(ids);
    if (result > 0) {
      for (Long medicationId : medicationIds) {
        updateMedicationStockAndPrice(medicationId);
      }
    }
    return result;
  }

  /**
   * 删除药物库存信息
   * 
   * @param id 药物库存主键
   * @return 结果
   */
  @Override
  public int deleteMedicationStockById(Long id) {
    MedicationStock stock = medicationStockMapper.selectMedicationStockById(id);
    int result = medicationStockMapper.deleteMedicationStockById(id);
    if (result > 0 && stock != null) {
      updateMedicationStockAndPrice(stock.getMedicationId());
    }
    return result;
  }

  /**
   * 修改药品库存信息
   * 
   * @param medicationId 药品ID
   * @param quantity     药品数量
   * @return 结果
   */
  @Override
  public int decreaseStock(Long medicationId, Long quantity) {
    List<MedicationStock> stocks = medicationStockMapper.selectMedicationStockByMedicationId(medicationId);
    if (stocks == null || stocks.isEmpty()) {
      throw new RuntimeException("药品库存不存在");
    }

    Long remainingQuantity = quantity;
    for (MedicationStock stock : stocks) {
      if (remainingQuantity <= 0) {
        break;
      }

      Long availableQuantity = stock.getQuantity();
      if (availableQuantity > 0) {
        Long deductQuantity = Math.min(availableQuantity, remainingQuantity);
        stock.setQuantity(availableQuantity - deductQuantity);
        medicationStockMapper.updateMedicationStock(stock);
        remainingQuantity -= deductQuantity;
      }
    }

    if (remainingQuantity > 0) {
      throw new RuntimeException("药品库存不足");
    }

    return 1;
  }
}